package com.util;

import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class voice  extends JFrame{


    static JTextArea read_Text = new JTextArea();//收到数据显示区域，接收到的数据都显示到该区域
    //	static JTextArea jdq_Text = new JTextArea();//收到继电器状态数据显示区域。
//	static JTextArea kgl_Text = new JTextArea();//收到开关量状态数据显示区域。
    static Socket Client;
    static Thread t_read;
    public  voice()
    {
        JFrame frame = new JFrame("科星互联（www.corxnet.com）");
        // Setting the width and height of frame
        frame.setSize(1000, 600);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();
        frame.add(panel);
        panel.setBackground(Color.white) ;
        placeComponents(panel);
        frame.setVisible(true);

    }

    private static void placeComponents(JPanel panel) {
        panel.setLayout(null);

        read_Text.setBackground(Color.BLACK);
        read_Text.setForeground(Color.YELLOW);

        JScrollPane js=new JScrollPane(read_Text);
        js.setBounds(80,50,500,450);
        panel.add(js);
        //分别设置水平和垂直滚动条自动出现
        js.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        js.setHorizontalScrollBarPolicy(
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);


        JLabel ip_label=new JLabel("服务器IP:");
        ip_label.setBounds(80, 20, 70, 25);
        panel.add(ip_label);

        JTextField IP_list=new JTextField("192.168.0.18"); //IP填写
        IP_list.setBounds(160, 20, 120, 25);
        panel.add(IP_list);


        JLabel port_label=new JLabel("服务器端口:");
        port_label.setBounds(290, 20, 70, 25);
        panel.add(port_label);
        JTextField PORT_text  = new JTextField("50000");//服务器端口号文本框
        PORT_text.setBounds(370, 20, 120, 25);
        panel.add(PORT_text);

        /***************创建Socket连接*****************/
        JButton btn_connect=new JButton("连接");

        btn_connect.setBounds(500, 20, 100, 25);
        panel.add(btn_connect);
        btn_connect.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub

                if(btn_connect.getText()=="连接")
                {
                    int port=50000;
                    try {
                        port=Integer.parseInt(PORT_text.getText());
                    }
                    catch(Exception err)
                    {

                    }
                    try {
                        Client=new Socket(IP_list.getText(),port);
                        btn_connect.setText("断开连接");
                        /***************创建一个线程用于监听收到的数据*****************/
                        t_read= new Thread(new ThreadReadSocket(Client));
                        t_read.start();
                    } catch (UnknownHostException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }

                }
                else if(btn_connect.getText()=="断开连接")
                {

                    try {
                        Client.close();
                        btn_connect.setText("连接");
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                }
            }

        });


        JPanel pl_voice = new JPanel();
        pl_voice.setLayout(null);
        pl_voice.setBorder(BorderFactory.createTitledBorder( "语音播报"));
        pl_voice.setBounds(600,260,350,100);
        panel.add(pl_voice);
        pl_voice.setBackground(Color.white);

        JTextField txt_data  = new JTextField();
        txt_data.setBounds(5, 40, 340, 20);
        pl_voice.add(txt_data);

        JButton btn_send=new JButton("语音播报");
        btn_send.setBounds(120, 70, 90, 20);
        pl_voice.add(btn_send);
        btn_send.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub

                try {
                    if(Client!=null) {
                        if(!Client.isClosed()) {


                            /***************发送数据*****************/
                            OutputStream out = Client.getOutputStream();
                            /***************将GB2312编码字符串转换为字节数组发送*****************/
                            out.write (("#"+txt_data.getText()).getBytes("GB2312"));
                            SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            read_Text.append(time.format(new Date())+" 下发指令：#"+txt_data.getText()+"\n");
                            read_Text .selectAll();
                        }
                    }
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });



        JButton btn_eliminate=new JButton("清除窗口");

        btn_eliminate.setBounds(490, 510, 90, 20);
        panel.add(btn_eliminate);
        btn_eliminate.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                read_Text.setText("");
            }});

        JPanel pl_kgl = new JPanel();
        pl_kgl.setLayout(null);
        pl_kgl.setBorder(BorderFactory.createTitledBorder( "输入输出监控(仅限带输入输出的设备)"));
        pl_kgl.setBounds(600,50,350,210);
        panel.add(pl_kgl);
        pl_kgl.setBackground(Color.white);

        JButton btn_kgl=new JButton("读取开关量状态");
        btn_kgl.setBounds(100, 20, 120, 20);
        pl_kgl.add(btn_kgl);
        btn_kgl.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub

                try {
                    if(Client!=null) {
                        if(!Client.isClosed()) {
                            /***************下发读取开关量状态指令*****************/
                            OutputStream out = Client.getOutputStream();
                            out.write (hexStringToByteArray("04FFFFFF"));
                            SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            read_Text.append(time.format(new Date())+" 下发指令：04FFFFFF\n");
                            read_Text .selectAll();
                        }
                    }
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });

        JPanel pl_jdq = new JPanel();
        pl_jdq.setLayout(null);
        pl_jdq.setBorder(BorderFactory.createTitledBorder( "继电器控制"));
        pl_jdq.setBounds(10,50,330,150);
        pl_kgl.add(pl_jdq);
        pl_jdq.setBackground(Color.white);

        JLabel lb_time =new JLabel("控制时间");
        lb_time.setBounds(170,20,50,20);
        pl_jdq.add(lb_time);


        JTextField txt_time=new JTextField("10");
        txt_time.setBounds(225,20,50,20);
        txt_time.addKeyListener(new KeyAdapter() {
            public void keyTyped(KeyEvent e) {
                if(e.getKeyChar()<KeyEvent.VK_0||e.getKeyChar()>KeyEvent.VK_9) {
                    e.consume();
                }else {
                    System.out.print(e.getKeyChar());
                }
            }
        });

        pl_jdq.add(txt_time);

        JLabel lb_init =new JLabel("100MS");
        lb_init.setBounds(275,20,50,20);
        pl_jdq.add(lb_init);
        lb_time.setVisible(false);
        txt_time.setVisible(false);
        lb_init.setVisible(false);

        JLabel lb_type =new JLabel("控制方式");
        lb_type.setBounds(20,20,50,20);
        pl_jdq.add(lb_type);

        JComboBox com_type=new JComboBox();
        com_type.setBounds(80, 20, 80, 20);
        com_type.addItem("普通控制");
        com_type.addItem("点动控制");
        pl_jdq .add(com_type);

        com_type.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                int index=((JComboBox)e.getSource()).getSelectedIndex();//获取到选中项的索引
                if(index==1)
                {

                    lb_time.setVisible(true);
                    txt_time.setVisible(true);
                    lb_init.setVisible(true);
                }
                else if(index==0) {
                    lb_time.setVisible(false);
                    txt_time.setVisible(false);
                    lb_init.setVisible(false);}
            }
        });

        JLabel lb_munber =new JLabel("控制路数");
        lb_munber.setBounds(20,50,50,20);
        pl_jdq.add(lb_munber);

        JComboBox com_munber=new JComboBox();
        com_munber.setBounds(80, 50, 80, 20);
        com_munber.addItem("第一路");
        com_munber.addItem("第二路");
        pl_jdq .add(com_munber);

        JComboBox com_action=new JComboBox();
        com_action.setBounds(180, 50, 80, 20);
        com_action.addItem("打开");
        com_action.addItem("关闭");
        pl_jdq .add(com_action);

        JButton btn_jdq=new JButton("下发控制");
        btn_jdq.setBounds(120, 80, 90, 20);
        pl_jdq.add(btn_jdq);
        btn_jdq.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub

                try {
                    if(Client!=null) {
                        if(!Client.isClosed()) {
                            /***************下发继电器控制指令（生成控制指令）*****************/
                            String send_data="";

                            if(com_type.getSelectedIndex()==0)
                            {
                                if(com_munber.getSelectedIndex()==0)
                                {
                                    if(com_action.getSelectedIndex()==0) {
                                        send_data="0301FFFF";
                                    }
                                    else { send_data="0201FFFF";}

                                }
                                else if(com_munber.getSelectedIndex()==1)
                                {
                                    if(com_action.getSelectedIndex()==0) {
                                        send_data="0302FFFF";
                                    }
                                    else { send_data="0202FFFF";}
                                }
                            }
                            else if(com_type.getSelectedIndex()==1)
                            {

                                if(com_munber.getSelectedIndex()==0)
                                {
                                    String time= Integer.toHexString(Integer.parseInt(txt_time.getText()));
                                    if(Integer.parseInt(txt_time.getText())>=1&&Integer.parseInt(txt_time.getText())<=255)
                                    {
                                        if(time.length()==1)
                                        {
                                            time="0"+time;
                                        }

                                    }

                                    send_data="05"+time+"FFFF"  ;
                                }
                                else if(com_munber.getSelectedIndex()==1)
                                {
                                    String time= Integer.toHexString(Integer.parseInt(txt_time.getText()));
                                    if(Integer.parseInt(txt_time.getText())>=1&&Integer.parseInt(txt_time.getText())<=255)
                                    {
                                        if(time.length()==1)
                                        {
                                            time="0"+time;
                                        }

                                    }

                                    send_data="06"+time+"FFFF"  ;
                                }
                            }
                            OutputStream out = Client.getOutputStream();
                            out.write (hexStringToByteArray(send_data));
                            SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            read_Text.append(time.format(new Date())+" 下发指令："+send_data+"\n");
                            read_Text .selectAll();
                        }
                    }

                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });

        JButton btn_openall=new JButton("全开");
        btn_openall.setBounds(40, 110, 90, 20);
        pl_jdq.add(btn_openall);
        btn_openall.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                try {
                    if(Client!=null) {
                        if(!Client.isClosed()) {
                            OutputStream out = Client.getOutputStream();
                            out.write (hexStringToByteArray("0303FFFF"));
                            SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            read_Text.append(time.format(new Date())+" 下发指令：0303FFFF\n");
                            read_Text .selectAll();
                        }
                    }

                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }});
        JButton btn_closeall=new JButton("全闭");
        btn_closeall.setBounds(140, 110, 90, 20);
        pl_jdq.add(btn_closeall);
        btn_closeall.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                try {
                    if(Client!=null) {
                        if(!Client.isClosed()) {
                            OutputStream out = Client.getOutputStream();
                            out.write (hexStringToByteArray("0203FFFF"));
                            SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            read_Text.append(time.format(new Date())+" 下发指令：0203FFFF\n");
                            read_Text .selectAll();
                        }
                    }

                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }});
    }

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        voice c=new voice();

    }




    //十六进制字符串转化为字节数组
    public static byte[] hexStringToByteArray(String hexString) {
        hexString = hexString.replaceAll(" ", "");
        int len = hexString.length();
        if(len%2!=0)
        {
            len=len+1;
            hexString="0"+hexString;
        }
        byte[] bytes = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            // 两位一组，表示一个字节,把这样表示的16进制字符串，还原成一个字节

            bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character
                    .digit(hexString.charAt(i + 1), 16));
        }
        return bytes;
    }

    //字节数组转化为十六进制
    public static String bytesToHex(byte[] bytes) {
        String r = "";

        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            r += hex.toUpperCase();
        }

        return r;


    }

}
class ThreadReadSocket implements Runnable {

    private Socket client;

    private int BUFFER_SIZE = 50;

    public ThreadReadSocket(Socket i) {
        // TODO Auto-generated constructor stub
        client = i;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            //声明一个输入流监听客户端数据
            InputStream in = client.getInputStream();
            OutputStream out =client.getOutputStream();
            //OutputStream out = client.getOutputStream();
            byte[] recData = null;
            int munber =0;
            while(true) {
                if(client.isClosed()) {
                    break;
                }
                else
                {
                    try
                    {
                        recData = new byte[1024];
                        //从输入流中读取客户端数据
                        int size = in.read(recData);
                        //System.out.println(size);
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        if(size>-1)
                        {

                            byte[] new_data=new byte[size]	;
                            //截取有用数据放到新数组
                            new_data=Arrays.copyOf(recData,size);
                            String data = voice.bytesToHex(new_data);


                            if(data=="4F4B") {	voice.read_Text.append(df.format(new Date())+" 收到回复：OK\n");}
                            else if(data=="0800"){	voice.read_Text.append(df.format(new Date())+" 收到回复：OL\n");}
                            else voice.read_Text.append(df.format(new Date())+" 收到回复："+data+"\n");{}

                            voice.read_Text .selectAll();



                        }else {

                            System.out.println("数据读取完毕！");


                            client.close();

                            break;
                            //ss.close();
                        }
                    }
                    catch(java.net.SocketException err)
                    {
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                        voice.read_Text.append(df.format(new Date())+" 已断开连接！！\n");
                        voice.read_Text .selectAll();
                        client.close();
                    }
                }
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }

}
